# -*- coding:utf-8 -*-
"""
作者：祁康伟
日期：2024/01/12  11:14
"""
import numpy as np
import pandas as pd
from datetime import datetime
import time
import logging

logger = logging.getLogger('pojie_A10.computing_method_A10')


# 异或校验
def XOR_verification(str1):
    res = None
    for x in range(0, len(str1), 2):
        hex_str = int("0x" + str1[x:x + 2], 16)  # 把16进制转10进制
        if x:
            # 第一个
            res ^= hex_str
        else:
            res = hex_str ^ 0
    ret = hex(res).upper()[2:]
    if len(ret) != 2:
        ret = '0' * (2 - len(ret)) + ret
    return ret


# 压力速度设定值、实时值
def real_time_value_of_pressure_and_velocity(pressure_speed_list):
    # 计算射胶过程中的   实际压力、速度  设定压力、速度

    out_arr = {}
    # 一、设定压力、速度   5Hz
    processing_signal_data_list = pressure_speed_list
    df = pd.DataFrame(processing_signal_data_list)

    df = df[df[3] == "00"]  # 动作信号是射胶的
    tm = list(df[0])  # 时间
    actual_pressure = list(df[4])  # 实际压力
    actual_speed = list(df[5])  # 实际速度
    settings_pressure = list(df[6])  # 设定压力
    settings_speed = list(df[7])  # 设定速度

    # # 得到一个重采样后的二维列表，        时间    设定压力    设定速度
    # settings_pressure_speed_downsampling = standardized_sampling(np.array([list(tm), list(actual_pressure), list(actual_speed), list(settings_pressure), list(settings_speed)]).T)
    # out_arr["实际压力"] = list(np.array(settings_pressure_speed_downsampling)[:, 1])
    # out_arr["实际速度"] = list(np.array(settings_pressure_speed_downsampling)[:, 2])
    # out_arr["设定压力"] = list(np.array(settings_pressure_speed_downsampling)[:, 3])
    # out_arr["设定速度"] = list(np.array(settings_pressure_speed_downsampling)[:, 4])

    out_arr["实际压力"] = actual_pressure
    out_arr["实际速度"] = actual_speed
    out_arr["设定压力"] = settings_pressure
    out_arr["设定速度"] = settings_speed

    return out_arr


# 升采样、降采样
def standardized_sampling(sample_frame_list):
    df = pd.DataFrame(np.array(sample_frame_list))
    df.index = pd.to_datetime(pd.to_datetime(df[0]))
    df1 = df.resample('100L').last().ffill()
    df1[0] = df1.index
    df1[0] = df1[0].apply(lambda x: str(x))
    for _ in range(1, len(sample_frame_list[0])):
        df1[_] = df1[_].apply(lambda x: eval(x))
    sample_frame_list_downsampling = df1.resample('100L').last().ffill().values.tolist()
    return sample_frame_list_downsampling


# 计算温度实际值
def calculate_the_actual_temperature_value(real_time_temperature_data):
    out_arr = {}
    out_arr["射嘴温度"] = real_time_temperature_data["tmp0"]
    out_arr["一段温度"] = real_time_temperature_data["tmp1"]
    out_arr["二段温度"] = real_time_temperature_data["tmp2"]
    out_arr["三段温度"] = real_time_temperature_data["tmp3"]
    out_arr["四段温度"] = real_time_temperature_data["tmp4"]
    out_arr["五段温度"] = real_time_temperature_data["tmp5"]
    out_arr["六段温度"] = real_time_temperature_data["tmp6"]
    out_arr["七段温度"] = real_time_temperature_data["tmp7"]
    out_arr["八段温度"] = real_time_temperature_data["tmp8"]

    return out_arr


# 计算统计值
def calculate_statistical_values(processing_signal_data_list, statistical_parameter_row_identification):
    dict_statistics = {"周期计时": "", "注射保压时间": "", "射出时间": "", "储料时间": "", "合模时间": "",
                       "合模低压时间": "", "合模高压时间": "", "开模时间": "", "开模位置": "", "射胶信号": "",
                       "射出终点": "", "射出监控": "", "射出起点": "", "转保压压力": "", "最大储料转速": "",
                       "射退时间": "", "托模时间": "", "射出尖压": "", "储料尖压": "", "顶进时间": "",
                       "顶退时间": "", "取件时间": "", "最大射速": "", "保压时间": "", "冷却时间": "",
                       }
    out_arr = {}
    df = pd.DataFrame(processing_signal_data_list)
    out_arr["机台状态"] = processing_signal_data_list[-1][11]  # 机台状态取二维数组最后一个
    for i in dict_statistics.keys():
        try:
            out_arr[i] = statistical_parameter_row_identification[i]
        except:
            pass

    # out_arr["合模时间"] = str(round(len(df.loc[df[10] == 1]) / 8, 2))  # 这里的除以5   是根据该字段的频率而定的
    # out_arr["冷却时间"] = str(round(len(df.loc[df[12] == "0200"]) / 8, 2))
    # out_arr["开模时间"] = str(round(len(df.loc[df[10] == 4]) / 8, 2))

    return out_arr


# 处理射嘴温度、1段到8段
# 030200294344————实时温度数据（2.5HZ，88位）
def nozzle_temperature_1_8(frame_bytes, real_time_temperature_data):
    # (frame_bytes[10:14] + frame_bytes[10:14][:2])[-4:]  # 高低位转换
    # 射嘴温度 3
    real_time_temperature_data["tmp0"] = round(int((frame_bytes[504:508] + frame_bytes[504:508][:2])[-4:], 16) / 10, 1)
    # 第一段温度 4
    real_time_temperature_data["tmp1"] = round(int((frame_bytes[508:512] + frame_bytes[508:512][:2])[-4:], 16) / 10, 1)
    # 第二段温度 5
    real_time_temperature_data["tmp2"] = round(int((frame_bytes[512:516] + frame_bytes[512:516][:2])[-4:], 16) / 10, 1)
    # 第三段温度 6
    real_time_temperature_data["tmp3"] = round(int((frame_bytes[516:520] + frame_bytes[516:520][:2])[-4:], 16) / 10, 1)
    # 第四段温度 7
    real_time_temperature_data["tmp4"] = round(int((frame_bytes[520:524] + frame_bytes[520:524][:2])[-4:], 16) / 10, 1)
    # 第五段温度 8
    real_time_temperature_data["tmp5"] = round(int((frame_bytes[524:528] + frame_bytes[524:528][:2])[-4:], 16) / 10, 1)
    # 第六段温度 9
    real_time_temperature_data["tmp6"] = round(int((frame_bytes[528:532] + frame_bytes[528:532][:2])[-4:], 16) / 10, 1)
    # 第七段温度 10
    real_time_temperature_data["tmp7"] = round(int((frame_bytes[532:536] + frame_bytes[532:536][:2])[-4:], 16) / 10, 1)
    # 第八段温度 11
    real_time_temperature_data["tmp8"] = round(int((frame_bytes[536:540] + frame_bytes[536:540][:2])[-4:], 16) / 10, 1)

    return real_time_temperature_data


# 处理实时压力、速度、设置压力、设置速度
def actual_settings_pressure_speed(frame_bytes, i):
    dongzuo, shijiyali, shijisudu, shezhiyali, shezhisudu, dongzuojishi = 30 + i * 32, 40 + i * 32, 44 + i * 32, 48 + i * 32, 52 + i * 32, 56 + i * 32
    dongzuo, shijiyali, shijisudu, shezhiyali, shezhisudu, dongzuojishi = int(dongzuo), int(shijiyali), int(shijisudu), int(shezhiyali), int(shezhisudu), int(dongzuojishi)
    # round(int((frame_bytes[502:506] + frame_bytes[502:506][:2])[-4:], 16) / 10, 1)
    frame_arr = []
    # 日期 0
    frame_arr.append(datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')),  # 日期 0
    # 时间戳 1  毫秒级别
    frame_arr.append(int(round(time.time() * 1000)))  # 时间戳 1  毫秒级别
    # 帧序列号自行标记
    # 帧序列号 2
    frame_arr.append(0)  # 帧序列号,每秒80帧 2
    # 动作信号 3
    frame_arr.append(str(frame_bytes[dongzuo - 2:dongzuo]))
    # 实际压力 4
    frame_arr.append(int((frame_bytes[shijiyali - 4:shijiyali] + frame_bytes[shijiyali - 4:shijiyali][:2])[-4:], 16))
    # 实际速度 5
    frame_arr.append(int((frame_bytes[shijisudu - 4:shijisudu] + frame_bytes[shijisudu - 4:shijisudu][:2])[-4:], 16))
    # 设置压力 6
    frame_arr.append(int((frame_bytes[shezhiyali - 4:shezhiyali] + frame_bytes[shezhiyali - 4:shezhiyali][:2])[-4:], 16))
    # 设置速度 7
    frame_arr.append(round(int((frame_bytes[shezhisudu - 4:shezhisudu] + frame_bytes[shezhisudu - 4:shezhisudu][:2])[-4:], 16) / 10, 2))
    # 动作计时 8
    frame_arr.append(int((frame_bytes[dongzuojishi - 4:dongzuojishi] + frame_bytes[dongzuojishi - 4:dongzuojishi][:2])[-4:], 16))

    return frame_arr
